import { getUserInfo, login, postInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    // 定义token
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      // 持久化Token
      setToken(token)
    },
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, payload) {
      const res = await login(payload)
      context.commit('updateToken', res.data)
      return res
    },
    // 获取列表信息
    async postUserInfo(context) {
      const res = await getUserInfo()
      // 在获取一次请求，请求员工列表信息
      const res1 = await postInfo(res.data.userId)
      context.commit('updateUserInfo', { ...res.data, ...res1.data })
      return { ...res.data, ...res1.data }
    },
    loginOut(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  },
  getters: {}
}
